import socket

def create_tcp_client(host='127.0.0.1', port=8888):
    # 创建 TCP socket
    client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    
    try:
        # 连接服务器
        client.connect((host, port))
        print(f"已连接到服务器 {host}:{port}")

        while True:
            # 输入要发送的消息
            message = input("prompt（'quit' 退出）$ ")

            if message.lower() == 'quit':
                break

            # 发送数据到服务器
            client.send(message.encode('utf-8'))

            # 接收服务器回显（但不自动打印 → 即“关闭回显”）
            response = client.recv(1024)
            
            print(f"收到回显: {response.decode('utf-8', errors='ignore')}")

            # 或者做其他处理（如日志、解析等），而不输出到终端
            # 示例：记录日志
            # with open("client.log", "a") as f:
            #     f.write(f"Sent: {message}, Received: {response.decode()}\n")

        print("正在断开连接...")

    except KeyboardInterrupt:
        print("\n客户端被中断")
    except ConnectionRefusedError:
        print("连接被拒绝，请检查服务器是否运行")
    except Exception as e:
        print(f"发生错误: {e}")
    finally:
        client.close()
        print("客户端已关闭")

# 运行客户端
if __name__ == "__main__":
    create_tcp_client()